package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.thread.UserThreadLocal;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserThreadLocal  userThreadLocal;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("authorization");
        if (StringUtils.isEmpty(authorization)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            throw new RuntimeException("token不能为空");
//            return false;
        }
        Claims claims = tokenService.parseToken(authorization);
        if (MapUtil.isEmpty(claims)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new RuntimeException("未获取到用户信息");
        }
        Long userId = MapUtil.get(claims, "userId", Long.class);
        if (ObjectUtils.isEmpty(userId)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new RuntimeException("未获取到用户id");
        }
        userThreadLocal.set(userId);
        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        log.info("移除局部线程变量：userThreadLocal.remove()");
        userThreadLocal.remove();
    }
}
